<!--
 * @Version: 1.0
 * @Date: 2021-05-20 11:17:50
 * @LastEditTime: 2021-07-15 18:37:22
 * @Description:
-->
<template>
  <el-select
    :loading="loading"
    :value="value"
    :disabled="disabled"
    clearable
    filterable
    :placeholder="placeholder"
    @input="inputHandler"
    @change="changeHandler"
  >
    <el-option
      v-for="(item, index) in list"
      :key="index"
      :label="item.label"
      :value="item.value"
      :disabled="item.disabled"
    />
  </el-select>
</template>

<script>
export default {
  name: 'AppSelect',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    optionsLabel: {
      type: String,
      default: ''
    },
    optionsValue: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean
    },
    disabledKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: [],
      loading: false
    }
  },
  computed: {},
  watch: {
    'params.shop_id'() {
      console.log('=====>>>>===')
      this.getList()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取list
    getList() {
      const vm = this
      vm.list = []
      vm.loading = true
      vm.$http.get(vm.url, { params: vm.params }).then(res => {
        const data = vm.url === '/shops/buyers' ? res.data.buyers.filter(e => e.status === 1) : res.data
        vm.list = data.map(e => {
          e['label'] = e[vm.optionsLabel]
          e['value'] = e[vm.optionsValue]
          if (vm.disabledKey) {
            const [key, value] = vm.disabledKey.split(':')
            e['disabled'] = e[key] === +value
          } else {
            e['disabled'] = false
          }
          return e
        })
        vm.loading = false
      })
    },
    // change
    changeHandler(e) {
      this.$emit('input', e)
      const item = this.list.find(ele => ele.value === e)
      this.$emit('change', item)
    },
    // input
    inputHandler(e) {
      this.$emit('input', e)
    }
  }
}
</script>

<style lang="scss" scoped></style>
